package com.hsy.bibc.modules.order;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.widget.DPCircleImageView;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.hsy.bibc.R;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.order.gsondata.OrderDetailGsonData;
import com.hsy.bibc.modules.view.ScrollExpandListView;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.utils.HttpUtil;
import com.hsy.bibc.utils.VolleyLoadPicture;

import java.util.ArrayList;
import java.util.List;

public class OrderDetailActivity extends CommonBaseActivityWithSimpleActionBar {

    protected DPCircleImageView avtar;
    protected TextView nickName;
    protected TextView description;
    protected TextView orderIdTextView;
    protected TextView orderTime;
    protected ScrollExpandListView listView;
    protected TextView totalCount;
    protected TextView totalScores;
    protected ScrollView scrollView;

    private GoodsListAdapter mGoodsListAdapter;

    private String orderId = "INVALID_ORDER_ID";
    private String orderType = "-1";
    private String url = "";

    private DPHttpUtil.HttpCallback callback = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            OrderDetailGsonData.Result result = DPGsonUtil.fromJson(response, OrderDetailGsonData.Result.class);
            if (null == result) {
                showToast("服务器内部错误!");
                CommonUtils.hideProgressDialog();
                return;
            }
            nickName.setText(result.getUser().getNickname());
//            DPPicassoUtil.load(OrderDetailActivity.this, result.getUser().getAvatar(), avtar);
            VolleyLoadPicture vlp = new VolleyLoadPicture(OrderDetailActivity.this, avtar);
            vlp.getmImageLoader().get(result.getUser().getAvatar(), vlp.getOne_listener());
            orderIdTextView.setText("订单号: " + result.getOrder_sn());
            orderTime.setText(result.getCreate_datetime_str());
            description.setText(result.getUser().getScore() + "积分");

            if (null != result.getOrder()) {
                mGoodsListAdapter = new GoodsListAdapter(OrderDetailActivity.this, result);
                listView.setAdapter(mGoodsListAdapter);
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollTo(0, 0);
                    }
                });
                totalCount.setText(String.format("合计%s件", result.getQty()));
                totalScores.setText(result.getScore() + "积分");
                totalCount.setVisibility(View.VISIBLE);
                if (result.getOrder().size() > 0) {
                    for (int i = 0; i < result.getOrder().size(); i++) {

                        listView.expandGroup(0);
                    }
                } else {
                    DPLogUtil.d("listData.getWaste()==0");
                }
            } else {
                totalScores.setText(result.getScore() + "积分");
                totalCount.setVisibility(View.GONE);
            }
            CommonUtils.hideProgressDialog();
            getContentView().setVisibility(View.VISIBLE);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            CommonUtils.hideProgressDialog();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_order_detail);
        setTitle(R.string.txt_order_detail);
        getContentView().setVisibility(View.GONE);
        initView();
    }

    private void initView() {
        avtar = (DPCircleImageView) findViewById(R.id.avtar);
        nickName = (TextView) findViewById(R.id.nick_name);
        description = (TextView) findViewById(R.id.description);
        orderIdTextView = (TextView) findViewById(R.id.order_id);
        orderTime = (TextView) findViewById(R.id.order_time);
        listView = (ScrollExpandListView) findViewById(R.id.list_view);
        totalCount = (TextView) findViewById(R.id.total_count);
        totalScores = (TextView) findViewById(R.id.total_scores);
        scrollView = (ScrollView) findViewById(R.id.scroll_view);

        listView.setGroupIndicator(null);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (isEmpty(getActivityStartExtra())) {
            return;
        }
        orderId = getActivityStartExtra()[0];
        orderType = getActivityStartExtra()[1];
        switch (orderType) {
            case "1":
                url = Consts.Apis.GET_ORDER_DETAIL_FP;
                break;
            case "2":
                url = Consts.Apis.GET_ORDER_DETAIL_DH;
                break;
            case "3":
                url = Consts.Apis.GET_ORDER_DETAIL_SY;
                break;
            default:
                DPLogUtil.d("type=-1");
                break;
        }
        CommonUtils.showProgressDialog(this);
        HttpUtil.httpGet(this, 0, url + "?id=" + orderId, callback);
    }

    public class GoodsListAdapter extends BaseExpandableListAdapter {
        private List<OrderDetailGsonData.Order> listData;
        private LayoutInflater mInflater;

        public GoodsListAdapter(Context context, OrderDetailGsonData.Result src) {
            listData = src.getOrder();
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        //得到子item需要关联的数据
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return (listData.get(childPosition).getChildren());
        }

        //得到子item的ID
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        //设置子item的组件
        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_confirm_order_child, null);

                childViewHolder = new ChildViewHolder();
                childViewHolder.init(convertView);
            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }
            childViewHolder.setData(listData.get(groupPosition).getChildren().get(childPosition));
            return convertView;
        }

        //获取当前父item下的子item的个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return listData.get(groupPosition).getChildren().size();
        }

        //获取当前父item的数据
        @Override
        public Object getGroup(int groupPosition) {
            return listData.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listData.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        //设置父item组件
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.item_confirm_order_group, null);
            TextView firstName = (TextView) convertView.findViewById(R.id.groupName);
            firstName.setText(listData.get(groupPosition).getName());

            ImageView parentRightImage = (ImageView) convertView.findViewById(R.id.parentRightImage);
            ImageView parentLeftImage = (ImageView) convertView.findViewById(R.id.parentLeftImage);
            if (!"".equals(listData.get(groupPosition).getImg()) && null != listData.get(groupPosition).getImg()) {
                DPPicassoUtil.with(OrderDetailActivity.this).load(listData.get(groupPosition).getImg()).into(parentLeftImage);
            }

            if (isExpanded) {
                parentRightImage.setRotation(90);
            } else {
                parentRightImage.setRotation(0);
            }
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ChildViewHolder {

            public OrderDetailGsonData.Children src;

            public TextView nameTextView, score;
            public TextView priceTextView;
            public ImageView increaceImageView;
            public TextView valueEditTextExt;
            public ImageView decreaceImageView;
            public TextView unitTextView;
            public TextView showTextView;
            public LinearLayout editAreaLinearLayout;

            public ChildViewHolder() {

            }

            public void init(View convertView) {
                convertView.setTag(this);

                score = (TextView) convertView.findViewById(R.id.score);
                nameTextView = (TextView) convertView.findViewById(R.id.name);
                priceTextView = (TextView) convertView.findViewById(R.id.price);
                increaceImageView = (ImageView) convertView.findViewById(R.id.increace);
                valueEditTextExt = (TextView) convertView.findViewById(R.id.value);
                decreaceImageView = (ImageView) convertView.findViewById(R.id.decreace);
                unitTextView = (TextView) convertView.findViewById(R.id.unit);
                showTextView = (TextView) convertView.findViewById(R.id.show);
                editAreaLinearLayout = (LinearLayout) convertView.findViewById(R.id.edit_area);
            }

            public void setData(OrderDetailGsonData.Children src) {
                if (null == src) {
                    DPLogUtil.e("src = null.");
                    return;
                }
                this.src = src;
                this.nameTextView.setText(src.getName());
//                this.score.setText(src.getScore() + "积分/个");
//                this.priceTextView.setText(src.getPrice() + "元" + "/" + src.getUnit());

                this.valueEditTextExt.setText("×" + String.valueOf(src.getQty()));
//                this.showTextView.setText(String.valueOf(src.getQty()));
            }
        }
    }
}
